<?php

namespace App\Http\Controllers\Admin\Admin;

use App\Http\Controllers\Admin\AdminController;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use App\Api\Exceptions\ApiCommonException;

class LoginController extends AdminController
{
    /**
     * 登录
     */
    public function login(Request $request)
    {
        $credentials = [
            'name' => $request->name,
            'password'  => $request->password,
            'status' => 1,
        ];

        try {
            if (! $token = Auth()->guard($this->guard)->attempt($credentials)) {
                throw ApiCommonException::loginError();
            }
        } catch (JWTException $e) {
            throw ApiCommonException::loginInvalidCredentials();
        }

        return $this->getResponseSuccess(compact('token'));
    }

    /**
     * 用户登陆退出
     */
    public function logout()
    {
        try {
            Auth()->guard($this->guard)->logout();
        } catch (JWTException $e) {
            throw ApiCommonException::loginInvalidCredentials();
        }

        return $this->getResponseSuccess();
    }

    //获取登陆用户信息
    public function loginInfo()
    {
        try {
            $data = Auth()->guard($this->guard)->user();
        } catch (JWTException $e) {
            throw ApiCommonException::loginInvalidCredentials();
        }

        return $this->getResponseSuccess($data);
    }

    /**
     * 用户授权token刷新
     */
    public function refreshToken()
    {
        try {
            $token = Auth()->guard($this->guard)->refresh();
        } catch (JWTException $e) {
            throw ApiCommonException::loginInvalidCredentials();
        }

        return $this->getResponseSuccess(compact('token'));
    }
}